package view;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectOutputStream;

import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

import serverMessage.ServerMessage;


/**
 * class MyProtocolSendMessage - send to the user updates for his dropbox
 */
public class MyProtocolSendMessage implements Runnable{
	 
	BufferedReader in; ObjectOutputStream out;
	Socket clientSocket;
	//the users messages queue
	ConcurrentHashMap<String, ConcurrentLinkedQueue<ServerMessage>> userStatusHash;
	 
	/**
	 * constructor
	 * @param in - input stream
	 * @param out - output stream
	 * @param clientSocket - the client socket
	 * @param userStatusHash - the users messages queue
	 */
	public MyProtocolSendMessage(BufferedReader in, ObjectOutputStream out, Socket clientSocket, ConcurrentHashMap<String, ConcurrentLinkedQueue<ServerMessage>> userStatusHash){
		this.in=in; this.out=out;
		this.clientSocket = clientSocket;
		this.userStatusHash = userStatusHash;
	 }
	
	/**
	 * send to the user updates for his dropbox
	 */
	public void run(){
		
		String userID;
		try {
			userID = in.readLine();
		
			//get the user message queue
			ConcurrentLinkedQueue<ServerMessage> messageQueue = userStatusHash.get(userID);
			    
			//the first message
			ServerMessage message = messageQueue.poll();
			  
			//send all the messsages in the queue
		    while (message!=null)
		    {
		    	System.out.println(message);
		    	out.writeObject(message);
		    	message = messageQueue.poll();
		    }
		    
		    //say that there is no more messages for now
		    out.writeObject(new ServerMessage(null, "bye", null, null, null));
		    
		    
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("my pr");
			e.printStackTrace();
		}
		finally {
			
			//close in,out,client socket			
			
			try {
				if (out!=null)
					out.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			try {
				if (in!=null)
					in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				if (clientSocket!=null)
					clientSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
		}

	}

}